<?php

namespace addons\qingdongams\controller;

use addons\qingdongams\model\Parts;
use addons\qingdongams\model\PersonCart;
use addons\qingdongams\model\PersonOrder;

class WebCarts extends WebIndexApi
{
    public function __construct()
    {
        parent::__construct();

    }

    // 购物车列表
    public function getList()
    {
        $limit = input("limit/d", 10);
        $name = input('name', '');
        $ids = input('ids', '');
        $where = ['person_id' => $this->personId];
        if ($name) {
            $partsWhere['name'] = ['like', '%' . $name . '%'];
            $pids = Parts::where($partsWhere)->column('id');
            $where['parts_id'] = ['in', $pids];
        }
        if ($ids) {
            $where['id'] = ['in', explode(',', $ids)];
        }
        $list = PersonCart::where($where)->with('parts')->order('id desc')->paginate($limit);
        $this->success('', $list);
    }

    // 加入购物车
    public function addCart()
    {
        $partsId = input('parts_id', '', 'intval');
        if (!$partsId) {
            $this->error('请上传备件id');
        }
        $model = new PersonCart();
        if ($model->where(['parts_id' => $partsId, 'person_id' => $this->personId])->find()) {
            $this->success('加入购物车成功！');
        }
        $res = $model->allowField(true)->save([
            'person_id' => $this->personId,
            'parts_id' => $partsId,
            'num' => 1 // 默认加入购物车1
        ]);
        if ($res) {
            $this->success('加入购物车成功！');
        } else {
            $this->error('加入失败！');
        }
    }

    // 变更购物车数量
    public function editNum()
    {
        $id = input('id', '', 'intval');
        $num = input('num', 0, 'intval');
        if (!$id) {
            $this->error('请上传购物车id');
        }
        if (!$num) {
            $this->error('请上传备件数量');
        }
        $model = new PersonCart();
        $res = $model->where('id', $id)->update(['num' => $num]);
        if ($res) {
            $this->success('成功！');
        } else {
            $this->error('失败');
        }
    }

    // 删除购物车
    public function delParts()
    {
        $ids = input('ids', '');
        if (!$ids) {
            $this->error('请上传购物车id');
        }
        $model = new PersonCart();
        $res = $model->where('id', 'in', explode(',', $ids))->delete();
        if ($res) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

}